package com.dzjcloud.dzj.upms.biz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dzjcloud.dzj.upms.biz.mapper.MenuMapper;
import com.dzjcloud.dzj.upms.api.entity.Menu;
import com.dzjcloud.dzj.upms.biz.service.MenuService;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单权限表(Menu)表服务实现类
 *
 * @author makejava
 * @since 2021-06-08 17:18:41
 */
@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    /**
     *  树状排序
     *
     * @return
     */
    @Override
    public List<Tree<String>> getTree() {
        //TODO 获取所有数据
        List<Menu> menus = baseMapper.selectList(Wrappers.<Menu>lambdaQuery().orderByAsc(Menu::getId).orderByAsc(Menu::getSort));

        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setWeightKey("permission");
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setDeep(5);

        List<Tree<String>> build = TreeUtil.build(menus, "0", treeNodeConfig,
                (treeMenus, tree) -> {
                    tree.setId(treeMenus.getId());
                    tree.setParentId(treeMenus.getParentId());
                    tree.setWeight(treeMenus.getPermission());
                    tree.setName(treeMenus.getName());
                    tree.putExtra("url",treeMenus.getPath());
                    tree.putExtra("icon",treeMenus.getIcon());
                    tree.putExtra("type",treeMenus.getType());
                    tree.putExtra("sort",treeMenus.getSort());
                });

        //排序
        sort(build);
        return build;
    }

    /**
     * 菜单排序
     */
    public void sort(List<Tree<String>> trees){
        //最外层排序排序
        Collections.sort(trees, new Comparator<Tree<String>>() {
            @Override
            public int compare(Tree<String> o1, Tree<String> o2) {
                if (Integer.valueOf(o1.get("sort").toString())>Integer.valueOf(o2.get("sort").toString())){
                    return 1;
                }
                if (Integer.valueOf(o1.get("sort").toString())<Integer.valueOf(o2.get("sort").toString())){
                    return -1;
                }
                return o1.get("sort").toString().compareTo( o2.get("sort").toString());
            }
        });
        //内层排序
        for (Tree<String> stringTree : trees) {
            if (CollUtil.isNotEmpty(stringTree.getChildren())){
                sort(stringTree.getChildren());
            }
        }
    }
}
